<template>
	<view>
		<view class="content">
			<empty v-if="tabBars.length === 0"></empty>
			<view v-else>
				<!-- 顶部选项卡 -->
				<view style="width: 100%; text-align: center;height: 90upx;	position: fixed;z-index: 99; ">
					<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
						<view v-for="(item,index) in tabBars" :key="item.tagUuid" class="nav-item" :class="{current: index === tabCurrentIndex}"
						 :id="'tab'+index" @click="changeTab(index)">
							{{item.tagName}}
						</view>
					</scroll-view>
				</view>
				<!-- 下拉刷新组件 -->
				<!-- <mix-pulldown-refresh ref="mixPulldownRefresh" :top="90"
					@refresh="onPulldownReresh" @setEnableScroll="setEnableScroll"> -->
				<!-- 内容部分 -->
				<scroll-view class="panel-scroll-box" scroll-y refresher-enabled="true" @refresherrefresh="onPulldownReresh"
				 @scrolltolower="loadMore" :refresher-triggered="triggered">
					<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">

						<swiper-item v-for="tabItem in tabBars" :key="tabItem.tagUuid">
							<scroll-view scroll-y style="height: 100%;">
								<!--
									* 新闻列表
									* 和nvue的区别只是需要把uni标签转为weex标签而已
									* class 和 style的绑定限制了一些语法，其他并没有不同
								-->
								<empty v-if="tabItem.newsList == 0"></empty>
								<view @click="navToDetails(item)" v-for="(item, index) in tabItem.newsList" :key="index" class="news-item"
								 v-else>
									<view :class="['title', 'title'+item.articleType]">{{item.title}}</view>
									<view :class="['img-list', 'img-list'+item.articleType, item.articleType!='1' ? 'img-list-single': '']">
										<view :class="['img-wrapper', 'img-wrapper'+item.articleType, item.articleType!='1' ? 'img-wrapper-single': '']">
											<image class="img" :src="item.coverImageUrl || noPhoto"></image>
											<view class="video-tip" v-if="item.articleType!='1'">
												<image class="video-tip-icon" src="">
												</image>
											</view>
										</view>
									</view>
									<!-- 空图片占位 -->
									<!-- <view v-if="!item.coverImageUrl" class="img-empty"></view> -->
									<view :class="['bot', 'bot'+item.articleType]">
										<text class="author">{{applicationConfig.applicationName}}</text>
										<text class="time">{{item.publishTime.replace(/T/," ").split(".")[0]}}</text>
									</view>
								</view>
								<!-- 上滑加载更多组件 -->
								<!-- <view v-if="tabItem.loadMoreStatus == ''"></view> -->
								<mix-load-more v-show="loadMoreStatus>-1" :status="loadMoreStatus"></mix-load-more>
							</scroll-view>
						</swiper-item>


					</swiper>
				</scroll-view>
				<!-- </mix-pulldown-refresh> -->
			</view>

		</view>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import json from '@/Json'
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	import empty from "@/components/empty";
	import {
		mapState,
		mapMutations
	} from 'vuex';
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			empty,
			uniLoadMore
		},
		data() {
			return {
				// mode:'',
				triggered: false,
				loadMoreStatus: 1, //加载更多 0加载前，1加载中，2没有更多了
				communityId: this.$api.util.getAreaCode(),
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				pageSize: 10,
				tagNameList: [],
				noPhoto: "https://cdjjyl.com.cn/images/noPhoto.png",
			}
		},
		computed: {
			...mapState(['hasLogin', 'userInfo', 'footPrint', 'applicationConfig', 'defaultCommunityId']),
			advertNavUrl() {
				let data = {
					title: '测试跳转新闻详情',
					author: '测试作者',
					time: '2019-04-26 21:21'
				}
				return `/pages/details/details?data=${JSON.stringify(data)}`;
			}
		},
		async onLoad() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		// onShow() {
		// 	this.loadMoreStatus = -1
		// 	this.loadTabbars();
		// },
		onReady() {
			/**
			 * 启动页广告 使用文档（滑稽）
			 * 1. 引入组件并注册
			 * 		import mixAdvert from '@/components/mix-advert/vue/mix-advert';
			 *      components: {mixAdvert},
					 <!-- #ifndef MP -->
						<mix-advert
							ref="mixAdvert"
							:timedown="8"
							imageUrl="/static/advert.jpg"
							:url="advertNavUrl"
						></mix-advert>
					<!-- #endif -->
			 * 	2. 调用组件的initAdvert()方法进行初始化
			 *
			 *  初始化的时机应该是在splash关闭时，否则会造成在app端广告显示了数秒后首屏才渲染出来
			 */
			// #ifndef MP
			// this.$refs.mixAdvert.initAdvert();
			// #endif
		},
		methods: {
			/**
			 * 数据处理方法在vue和nvue中通用，可以直接用mixin混合
			 * 这里直接写的
			 * mixin使用方法看index.nuve
			 */
			//获取分类
			loadTabbars() {
				let that = this;
				this.$api.request.inquiryTag({
					tagType: 'ARTICLE',
					areaCode: this.communityId
				}, function(res) {
					if (res.body.status.statusCode === '0') {
						let tabList = res.body.data.tags.slice(0, 3);
						console.log(tabList);
						tabList.forEach(item => {
							item.newsList = [];
							// item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
							item.refreshing = 0;
							item.pageNo = 1;
							that.tagNameList.push(item.tagName)
						})
						that.tabBars = tabList;

						if (tabList.length > 0) {
							that.loadNewsList('add');
						}
					}
				})
			},

			//新闻列表
			loadNewsList(type) {
				let that = this;
				let tabItem = this.tabBars[this.tabCurrentIndex];
				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (this.loadMoreStatus === 2) {
						return;
					}
					this.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif
				this.$api.request.articleList({
					tagDTO: {
						tagName: tabItem.tagName
					},
					startIndex: (tabItem.pageNo - 1) * this.pageSize,
					pageSize: this.pageSize,
					areaCode: this.communityId
				}, function(res) {
					if (res.body.status.statusCode === '0') {
						let newsList = res.body.data.articles;
						console.log(newsList);
						let total = res.body.data.totalCount;
						tabItem.newsList = tabItem.newsList.concat(newsList);

						//下拉刷新 关闭刷新动画
						if (type === 'refresh') {
							// that.$refs.mixPulldownRefresh && that.$refs.mixPulldownRefresh.endPulldownRefresh();
							// #ifdef APP-PLUS
							tabItem.refreshing = false;
							// #endif
							// tabItem.loadMoreStatus = 0;
							that.loadMoreStatus = tabItem.newsList.length >= total ? 2 : 0;
							that.triggered = false
						}
						//上滑加载 处理状态
						if (type === 'add') {
							that.loadMoreStatus = tabItem.newsList.length >= total ? 2 : 0;
						}
					}
				}, true)



				//setTimeout模拟异步请求数据
				// setTimeout(()=>{
				// 	let list = json.newsList;
				// 	list.sort((a,b)=>{
				// 		return Math.random() > .5 ? -1 : 1; //静态数据打乱顺序
				// 	})
				// 	if(type === 'refresh'){
				// 		tabItem.newsList = []; //刷新前清空数组
				// 	}
				// 	list.forEach(item=>{
				// 		item.id = parseInt(Math.random() * 10000);
				// 		tabItem.newsList.push(item);
				// 	})
				// 	//下拉刷新 关闭刷新动画
				// 	if(type === 'refresh'){
				// 		this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
				// 		// #ifdef APP-PLUS
				// 		tabItem.refreshing = false;
				// 		// #endif
				// 		tabItem.loadMoreStatus = 0;
				// 	}
				// 	//上滑加载 处理状态
				// 	if(type === 'add'){
				// 		tabItem.loadMoreStatus = tabItem.newsList.length > 40 ? 2: 0;
				// 	}
				// }, 600)
			},
			//新闻详情
			navToDetails(item) {
				console.log(item);
				let url = '';
				if (item.articleType === '1' && item.linkType == '自定义内容')
					url = '/package_biz/pages/content/details?id=' + item.articleUuid + '&flag=' + 1;
				if (item.articleType === '1' && item.linkType == '外部链接')
					url = '/package_biz/pages/content/webView?src=' + item.content;
				if (item.articleType === '2' || item.articleType === '3')
					url = '/package_biz/pages/content/videoDetails?id=' + item.articleUuid;
				uni.navigateTo({
					url: url,
					// success: function(res) {
					// 	// 通过eventChannel向被打开页面传送数据
					// 	res.eventChannel.emit('acceptDataFromOpenerPage', {
					// 		data: this.tagNameList
					// 	})
					// }
				})
			},

			//下拉刷新
			onPulldownReresh() {
				this.triggered = true
				let tabItem = this.tabBars[this.tabCurrentIndex];
				tabItem.refreshing = true;
				this.loadMoreStatus = -1
				this.resetPage(tabItem);
				this.loadNewsList('refresh');
			},
			//重置页码
			resetPage(tabItem) {
				tabItem.pageNo = 1;
				tabItem.newsList = [];
			},
			//上滑加载
			loadMore() {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				tabItem.pageNo = tabItem.pageNo + 1;
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e) {
				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;


					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (tabItem.loaded !== true) {
						this.resetPage(tabItem);
						this.loadMoreStatus = 1
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 300)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
		}
	}
</script>

<style lang='scss'>
	.content {
		background-color: $page-color-base;
		height: 100vh;
		position: relative;

	}

	.empty {
		margin-top: 40upx;
		text-align: center;
		color: $font-color-light;
		font-size: $font-base;
	}

	/* 顶部tabbar */
	.nav-bar {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		/* z-index: 999; */
		height: 90upx;
		white-space: nowrap;
		box-shadow: 0 2upx 8upx rgba(0, 0, 0, .06);
		background-color: #fff;

		.nav-item {
			display: inline-block;
			width: 250upx;
			height: 90upx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;

			&:after {
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid rgba(219, 63, 96, 1);
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}

		.current {
			color: rgba(219, 63, 96, 1);

			&:after {
				width: 50%;
			}
		}
	}

	.panel-content {
		width: 100%;
	}

	.swiper-box {
		height: 100%;
	}

	.panel-scroll-box {
		height: calc(100% - 100upx);
		position: absolute;
		top: 100upx;
		z-index: 10;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	/**
	 * 新闻列表 直接拿的nvue样式修改，,
	 * 一共需要修改不到10行代码, 另外px需要直接修改为upx，只有单位不一样，计算都是一样的
	 * 吐槽：难道不能在编译的时候把nuve中的upx转为px? 这样就不用修改单位了
	 */
	.video-wrapper {
		width: 100%;
		height: 440upx;

		.video {
			width: 100%;
		}
	}

	/* 	view {
		display: flex;
		flex-direction: column;
	} */

	.img {
		width: 100%;
		height: 100%;
	}

	.news-item {
		/* height: 300upx; */
		position: relative;
	}

	/* 修改结束 */

	/* 新闻列表  emmm 仅供参考 */
	.news-item {
		width: 750upx;
		padding: 16upx 30upx;
		border-bottom-width: 1px;
		border-color: #eee;
		background-color: #fff;
	}

	.title {
		font-size: 26upx;
		color: #303133;
		line-height: 46upx;
		height: 140upx;
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;
	}

	.bot {
		flex-direction: row;
	}

	.author {
		font-size: 24upx;
		color: #aaa;
	}

	.time {
		font-size: 24upx;
		color: #aaa;
	}

	.img-list {
		flex-shrink: 0;
		flex-direction: row;
		background-color: #fff;
		width: 260upx;
		height: 180upx;
	}

	.img-wrapper {
		flex: 1;
		flex-direction: row;
		height: 180upx;
		position: relative;
		overflow: hidden;
	}

	.img {
		flex: 1;
	}

	.img-empty {
		height: 20upx;
	}

	/* 图在左 */
	.img-list1 {
		position: absolute;
		left: 30upx;
		top: 24upx;
	}

	.title1 {
		padding-left: 280upx;
		word-wrap: break-all;
	}

	.bot1 {
		padding-left: 280upx;
		margin-top: 16upx;
	}

	/* 图在左 */
	.img-list2 {
		width: 700upx;
		margin: 16upx 0upx;
	}

	.title2 {
		padding-right: 210upx;
	}

	.bot2 {
		margin-top: 20upx;
	}

	/* 底部3图 */
	.img-list3 {
		width: 700upx;
		margin: 16upx 0upx;
	}

	.img-wrapper3 {
		margin-right: 4upx;
	}

	/* 底部大图 */
	.img-list-single {
		width: 690upx;
		height: 240upx;
		margin: 16upx 0upx;
	}

	.img-wrapper-single {
		height: 240upx;
		margin-right: 0upx;
	}

	.video-tip {
		position: absolute;
		left: 0;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, .3);
	}

	.video-tip-icon {
		width: 60upx;
		height: 60upx;
	}

	.mix-load-icon {
		/* width: 100% !important; */
		margin-right: 0 !important;
	}

	.mix-load-text {
		/* width: 100% !important; */
		z-index: 99 !important;
	}
</style>
